package xhwl.insurance.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import xhwl.android.common.log.XHLog;
import xhwl.android.common.util.StringUtil;
import xhwl.android.common.util.ToastUtil;
import xhwl.insurance.BaseActivity;
import xhwl.insurance.R;
import xhwl.insurance.adapter.SmartServiceAdapter;
import xhwl.insurance.animator.SlideInOutBottomItemAnimator;
import xhwl.insurance.customView.WrapContentLinearLayoutManager;
import xhwl.insurance.event.LayoutChangeEvent;
import xhwl.insurance.http.api.CommonProblemApi;
import xhwl.insurance.http.api.CustomerServiceApi;
import xhwl.insurance.http.bean.resp.CommonProblemResp;
import xhwl.insurance.http.bean.resp.CustomerServiceLeftResp;
import xhwl.insurance.http.bean.resp2.HttpResp;
import xhwl.insurance.util.AndroidBug5497Workaround;
import xhwl.insurance.util.KeyBoardUtils;
import xhwl.pulltorefresh.PullToRefreshRecyclerView;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * Created by fuyi on 2017/10/8.
 */

public class SmartServiceActivity extends BaseActivity implements View.OnClickListener {
    Button tv_customerservicesend;
    EditText edit_customerservicesend;
    ArrayList<CustomerServiceLeftResp> context_list = new ArrayList();
    SmartServiceAdapter adapter;
    LinearLayout linear_rengong;


    private PullToRefreshRecyclerView recyclerView;
    WrapContentLinearLayoutManager layoutManager;
    int mPage = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_customer_service);
        AndroidBug5497Workaround.assistActivity(this);

    }


    @Override
    protected boolean handleETTouchEvent() {
        return false;
    }

    @Override
    protected void setUpTitleView() {
        super.setUpTitleView();
        titleTextView.setText("智能客服");
    }
    @Override
    public void initViews() {
        initTitleViews();
        linear_rengong= (LinearLayout) findViewById(R.id.linear_rengong);
        tv_customerservicesend = (Button) findViewById(R.id.tv_customerservicesend);
        edit_customerservicesend = (EditText) findViewById(R.id.edit_customerservicesend);
        recyclerView = (PullToRefreshRecyclerView) findViewById(R.id.recyclerView);

        initRecylerView();
        adapter = new SmartServiceAdapter(SmartServiceActivity.this, context_list,handler);
        recyclerView.setAdapter(adapter);

    }

    private void initRecylerView() {
        //设置EmptyView
        View emptyView = View.inflate(mContext, R.layout.layout_empty_view, null);
        emptyView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        recyclerView.setEmptyView(emptyView);

        layoutManager = new WrapContentLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new SlideInOutBottomItemAnimator(recyclerView));

        //设置是否开启上拉加载
        recyclerView.setLoadingMoreEnabled(false);
        //设置是否开启下拉刷新
        recyclerView.setPullRefreshEnabled(false);
        //设置是否显示上次刷新的时间
        recyclerView.displayLastRefreshTime(false);
//        recyclerView.setRefreshLimitHeight(DimenUtil.dip2px(mActivity,50));
        recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
    }

    @Override
    public void initListener() {
        linear_rengong.setOnClickListener(this);
        tv_customerservicesend.setOnClickListener(SmartServiceActivity.this);
        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView view, int scrollState) {
                // TODO Auto-generated method stub
                switch (scrollState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
//                        adapter.handler.removeCallbacksAndMessages(null);
//                        adapter.notifyDataSetChanged();
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:
//                        adapter.handler.removeCallbacksAndMessages(null);
//                        tbAdapter.setIsGif(false);
//                        tbAdapter.isPicRefresh = true;
//                        reset();
                        KeyBoardUtils.hideKeyBoard(SmartServiceActivity.this,
                                edit_customerservicesend);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

            }
        });
    }

    @Override
    public void loadData() {
        final CustomerServiceLeftResp resp = new CustomerServiceLeftResp();

        CommonProblemApi api=new CommonProblemApi("常见问题");
        HttpManager.getInstance().dealHttp(SmartServiceActivity.this, api, new OnNextListener<HttpResp<ArrayList<CommonProblemResp>>>() {
            @Override
            public void onNext(HttpResp<ArrayList<CommonProblemResp>> arrayListHttpResp) {
                String s = "";
                for (int i=0;i<arrayListHttpResp.data.size();i++){
                   s = s+"Q"+(i+1)+":\t"+arrayListHttpResp.data.get(i).ANSWER_TITLE+"\n\n";
                }
                resp.setANSWER_CONTENT(getString(R.string.smart_service)+s);
                resp.setIS_LEFT(0);
                addMsg(resp);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.linear_rengong:
                startActivity(new Intent(SmartServiceActivity.this,StaffServiceActivity.class)
                        .putExtra("BACK_STATE","0"));
//                ToastUtil.showToast(mContext, "程序员还在开发中，敬请期待哦!");
                break;
            case R.id.tv_customerservicesend:
                String sendContent = edit_customerservicesend.getText().toString();
                if (StringUtil.isEmpty(sendContent)) {
                    ToastUtil.showToast(mContext, "发送内容不能为空！");
                    return;
                }
                reply(sendContent);
                edit_customerservicesend.setText("");
                break;

        }
    }

    private void addMsg(CustomerServiceLeftResp bean){
        context_list.add(bean);
        adapter.notifyDataSetChanged();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                recyclerView.smoothScrollToPosition(context_list.size() );
            }
        },200);//需要延迟scroll
    }

    public void onEvent(LayoutChangeEvent event){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                recyclerView.smoothScrollToPosition(context_list.size() );
            }
        },200);//需要延迟scroll
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    public void reply(String sendContent){
        CustomerServiceLeftResp bean = new CustomerServiceLeftResp();
        bean.setIS_LEFT(1);
        bean.ANSWER_CONTENT = sendContent;
        addMsg(bean);

        CustomerServiceApi api = new CustomerServiceApi(sendContent);
        HttpManager.getInstance().dealHttp(SmartServiceActivity.this, api, new OnNextListener<HttpResp<CustomerServiceLeftResp>>() {
            @Override
            public void onNext(HttpResp<CustomerServiceLeftResp> resp) {
                if (resp != null) {
                    if (resp.isOk()) {
                        final  CustomerServiceLeftResp bean = new CustomerServiceLeftResp();
                        bean.setIS_LEFT(0);
                        if (resp.data.getANSWER_CONTENT().equals("")) {
                            bean.setANSWER_CONTENT(getString(R.string.no_seekout));
                        } else {
                            bean.setANSWER_CONTENT(resp.data.getANSWER_CONTENT());
                        }
                        addMsg(bean);
                    }
                }
            }
        });
    }
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            String problem=(String)msg.obj;
            reply(problem.substring(4,problem.length()).trim());
            super.handleMessage(msg);
        }
    };
}
